package com.lxx.securitydemo2.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lxx.securitydemo2.domain.entity.LoginUser;
import com.lxx.securitydemo2.domain.entity.User;
import com.lxx.securitydemo2.service.MenuService;
import com.lxx.securitydemo2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据用户名查询用户信息  模拟数据库查询
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUserName, username);
        User user = userService.getOne(userLambdaQueryWrapper);

        //如果查询不到数据就通过抛出异常来给出提示
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 根据用户查询权限信息 添加到LoginUser中
        List<String> permissions = menuService.selectPermissionsByUserId(user.getId());

        //封装成UserDetails对象返回
        return new LoginUser(user, permissions);
    }
}
